package com.xydtech.ecard.ecard.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xydtech.common.annotation.PassToken;
import com.xydtech.common.annotation.RsaRequest;
import com.xydtech.common.enums.ResultStatus;
import com.xydtech.common.model.ResponseModel;
import com.xydtech.common.utils.StringUtils;
import com.xydtech.common.utils.http.HttpClientUtil;
import com.xydtech.ecard.ecard.service.IEcardAccessRecordListService;
import com.xydtech.ecard.user.domain.EcardApiUserInfo;
import com.xydtech.ecard.user.service.IEcardApiUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 电子名片营销任务Controller
 *
 * @author Daniel
 * @date 2021-09-14
 */
@Controller
@Api(tags = "电子名片-营销任务")
@RequestMapping("/ecardSaasApi/marketing")
public class EcardApiMarketingController extends EcardApiBaseController {
    @Autowired
    private IEcardApiUserService ecardApiUserService;
    @Autowired
    private IEcardAccessRecordListService ecardAccessRecordListService;
    /**
     * 电子名片营销接口服务地址
     */
    @Value("${url.apiMarketingUrl}")
    private String apiMarketingUrl;

    /**
     * 电子名片-营销任务列表
     *
     * @return
     */
    @ApiOperation(value = "电子名片-查询营销任务列表", notes = "电子名片-查询营销任务列表")
    @ApiResponses({@ApiResponse(code = 0, message = "OK", response = ResponseModel.class)})
    @PostMapping("/semTaskList")
    @ResponseBody
    @RsaRequest(param = false)
    public ResponseModel semTaskList() {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            Map<String, Object> paramMap = new HashMap<>();
            String apiUrl = apiMarketingUrl + "/odsDataApi/semTaskList";
            paramMap.put("userCode", userInfo.getUserCode());
            //paramMap.put("userCode", "244881");
            String result = HttpClientUtil.doPost(apiUrl, null, paramMap);
            JSONObject json = JSON.parseObject(result);
            if ("0".equals(json.getString("code"))) {
                return ResponseModel.ok(json.getJSONArray("data"));
            }else{
                return ResponseModel.error(json.getString("msg"));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("查询营销任务列表失败");
        }
    }

    /**
     * 电子名片-查询营销任务详情
     *
     * @return
     */
    @ApiOperation(value = "电子名片-查询营销任务详情", notes = "电子名片-查询营销任务列表详情")
    @ApiResponses({@ApiResponse(code = 0, message = "OK", response = ResponseModel.class)})
    @PostMapping(value = "/semTaskInfo",consumes = "application/json")
    @ResponseBody
    @RsaRequest
    public ResponseModel semTaskInfo(@RequestBody String cardNumJson) {
        String salt = getSalt();//盐值
        try { //获取当前用户的信息
            if (StringUtils.isEmpty(cardNumJson)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }

            String cardNum = JSONObject.parseObject(cardNumJson).getString("cardNum");
            if (StringUtils.isEmpty(cardNum)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }

            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            Map<String, Object> paramMap = new HashMap<>();
            String apiUrl = apiMarketingUrl + "/odsDataApi/semTaskInfo";
            paramMap.put("userCode", userInfo.getUserCode());
            paramMap.put("cardNum", cardNum);
            String result = HttpClientUtil.doPost(apiUrl, null, paramMap);
            JSONObject json = JSON.parseObject(result);
            if ("0".equals(json.getString("code"))) {
                return ResponseModel.ok(json.getJSONObject("data"));
            }else{
                return ResponseModel.error(json.getString("msg"));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("查询营销任务失败");
        }
    }

    /**
     * 电子名片-保存营销任务
     *
     * @return
     */
    @PassToken
    @ApiOperation(value = "电子名片-保存营销任务", notes = "电子名片-保存营销任务")
    @ApiResponses({@ApiResponse(code = 0, message = "OK", response = ResponseModel.class)})
    @PostMapping("/addSemExecuteRecord")
    @ResponseBody
    public ResponseModel addSemExecuteRecord(@RequestBody JSONObject paramMap) {
        try { //获取当前用户的信息
            String salt = getSalt();//盐值
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            paramMap.put("userId",userInfo.getUserId());
            paramMap.put("userCode",userInfo.getUserCode());
            paramMap.put("userName",userInfo.getUserName());
            String apiUrl = apiMarketingUrl + "/odsDataApi/addSemExecuteRecord";

            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            // 以JSON的形式发送请求
            headers.setContentType(MediaType.APPLICATION_JSON);
            //将请求头部和参数合成一个请求
            HttpEntity<JSONObject> request = new HttpEntity<>(paramMap, headers);
            JSONObject json = restTemplate.postForObject(apiUrl, request, JSONObject.class);
            if ("0".equals(json.getString("code"))) {
                return ResponseModel.ok(json.getString("data"));
            }else{
                return ResponseModel.error(json.getString("msg"));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("保存失败，请联系管理员");
        }
    }


    /**
     * 电子名片-查询营销任务执行记录列表
     *
     * @return
     */
    @ApiOperation(value = "电子名片-查询营销任务执行记录列表", notes = "电子名片-查询营销任务执行记录列表")
    @ApiResponses({@ApiResponse(code = 0, message = "OK", response = ResponseModel.class)})
    @PostMapping(value = "/getCustSemList",consumes = "application/json")
    @ResponseBody
    @RsaRequest
    public ResponseModel getCustSemList(@RequestBody String cardNumJson) {
        try {
            String salt = getSalt();//盐值
            if (StringUtils.isEmpty(cardNumJson)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            String cardNum = JSONObject.parseObject(cardNumJson).getString("cardNum");
            if (StringUtils.isEmpty(cardNum)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            Map<String, Object> paramMap = new HashMap<>();
            String apiUrl = apiMarketingUrl + "/odsDataApi/custSemList";
            paramMap.put("userCode", userInfo.getUserCode());
            paramMap.put("cardNum",cardNum);
            String result = HttpClientUtil.doPost(apiUrl, null, paramMap);
            JSONObject json = JSON.parseObject(result);
            if ("0".equals(json.getString("code"))) {
                return ResponseModel.ok(json.getJSONArray("data"));
            }else{
                return ResponseModel.error(json.getString("msg"));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("查询数据失败");
        }
    }


}
